package com.itboye.mengwu.app.ui.aiwujia;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import test.FlowLayout;
import android.R.integer;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.adapter.YuErJingAdapter;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.ui.aizhiwu.GeRenActivity;
import com.itboye.mengwu.data.model.BiaoQianModel;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply;
import com.itboye.mengwu.data.model.TieZiBaoHanReply.GetAList;
import com.itboye.mengwu.data.presenter.BiaoQianPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

/**
 * 
 * 
 * 2016.5.04
 * 
 */
public class FragmentYuEr extends BaseFragment implements Observer,
		IXListViewListener {

	private XListView listview;
	TextView mama_share;
	TextView mama_quest;
	TextView care;
	TextView question;
	TextView question_show;
	List<ImageView> imageViews;
	View headermamafenxiang;
	TextView hot_talk;
	TieZiPresenter presenter;
	private YuErJingAdapter adapter;
	ArrayList<TieZiBaoHanReply.GetAList> aLists = new ArrayList<TieZiBaoHanReply.GetAList>();
	TextView biaoqian_show;
	TextView baby_years;
	TextView baby_sex;
	boolean click;
	BiaoQianPresenter biaoqianPresenter;
	ArrayList<BiaoQianModel> biaoqianlist = new ArrayList<BiaoQianModel>();
	FlowLayout flowLayout;
	// FlowLayout flowLayout2;
	FlowLayout content_flowlayout;
	int pageNo = 1;
	int count = 0;
	StringBuilder builder = new StringBuilder();
	TextView tv;
	LuntanTieZiBean model = new LuntanTieZiBean();
	String authorID;
	String fid = "7";
	String type = "load";
	boolean tag = true;
	String zuixin = "1";
	int di;
	// ImageView tiwen, fenxiang;
	TextView tiwen_tv;

	@Override
	public int initView() {

		return R.layout.yuerjing_layout;
	}

	@Override
	public void onMyActivityCreated() {

		// MyJsonRequest<TieZiBaoHanReply> request = new
		// MyJsonRequest.Builder<TieZiBaoHanReply>()
		// .apiVer("100").typeKey("BY_ForumThread_query").param("fid", 7)
		// .requestListener(new XRequestListener<TieZiBaoHanReply>() {
		//
		// @Override
		// public void onResponse(TieZiBaoHanReply arg0) {
		// System.out.println("這是數據" + arg0);
		// aLists.clear();
		// aLists.addAll(arg0.getList());
		// adapter = new MyAdapter(getActivity(),
		// ImgOnClickListener);
		// listview.setAdapter(adapter);
		// for (int i = 0; i < arg0.getList().size(); i++) {
		// System.out
		// .println(aLists.get(i).getBabyDefault()
		// + "aLists.get(" + i
		// + ").getBabyDefault()");
		// }
		// }
		// }).errorListener(new XErrorListener() {
		//
		// @Override
		// public void onErrorResponse(Exception exception, int code,
		// String msg) {
		// }
		// }).build();
		// HttpRequest.getDefaultRequestQueue().add(request);
		showProgressDialog("数据加载中，请稍后", true);
		presenter = new TieZiPresenter(this);

		biaoqianPresenter = new BiaoQianPresenter(this);

		biaoqianPresenter.QueryBiaoQian(
				SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
				"2", "10");
		headermamafenxiang = LayoutInflater.from(getActivity()).inflate(
				R.layout.headeriew_mamafenxiang, null);
		flowLayout = (FlowLayout) headermamafenxiang
				.findViewById(R.id.flowLayout);
		tiwen_tv = (TextView) headermamafenxiang.findViewById(R.id.tiwen_tv);
		listview.addHeaderView(headermamafenxiang);
		adapter = new YuErJingAdapter(getActivity(), ImgOnClickListener,
				headclick, aLists, "0", deleteclick);
		listview.setAdapter(adapter);
		listview.setXListViewListener(this);
		listview.setPullLoadEnable(true);
		listview.setPullRefreshEnable(true);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 > 1) {
					Intent intent2 = new Intent(getActivity(),
							YuErJingMomDetailActivity.class);
					intent2.putExtra("tid", aLists.get(arg2 - 2).getTid());
					intent2.putExtra("title", aLists.get(arg2 - 2).getSubject());
					startActivity(intent2);
				}

			}
		});

	}

	OnClickListener headclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), GeRenActivity.class);
			intent.putExtra("uid",
					SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
							+ "");
			intent.putExtra("fromUid", v.getTag() + "");
			startActivity(intent);
		}

	};

	OnClickListener deleteclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// Intent intent = new Intent(getActivity(), GeRenActivity.class);
			// intent.putExtra("uid", uid);
			// intent.putExtra("fromUid", v.getTag() + "");
			// startActivity(intent);
		}

	};
	protected String tid;

	public void onResume() {
		super.onResume();
		model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model.setFid(fid);
		model.setPage_no(pageNo + "");
		model.setMaxReply("2");
		model.setFresh(zuixin);
		presenter.getInfo(model);
		adapter.notifyDataSetChanged();
	};

	OnClickListener ImgOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			tid = (String) v.getTag(R.id.tag_first);
			String isFav = (String) v.getTag(R.id.tag_second);
			di = (int) v.getTag(R.id.imgCollectionNum);
			if (judgeLogin()) {
				if ("0".equals(isFav)) {
					showProgressDialog("请求提交中，请稍后", true);
					presenter.dianzan(
							SPUtils.get(getActivity(), null,
									SpPublicParams.UID, "") + "", "1", tid);
					adapter.notifyDataSetChanged();

				} else {
					ByAlert.alert("已经点过赞了");

				}
			}

		}
	};

	public boolean judgeLogin() {
		if (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "" == null
				|| (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "")
						.equals("")) {
			Intent intent = new Intent(getActivity(), LoginActivity.class);
			startActivity(intent);
			return false;
		} else {
			return true;
		}
	}

	@Override
	protected void smartInject(View view) {
		// TODO Auto-generated method stub

		super.smartInject(view);
		mama_quest = (TextView) view.findViewById(R.id.mama_quest);
		mama_share = (TextView) view.findViewById(R.id.mama_share);
		// mama_share.setTextColor(getResources().getColor(R.color.main_color));
		// mama_quest.setTextColor(getResources().getColor(R.color.black));
		mama_quest.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@SuppressLint("ResourceAsColor")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (tag) {
					tiwen_tv.setText("妈妈提问");
					showProgressDialog("妈妈提问加载中，请稍后", true);
					mama_quest.setText("・妈妈提问・");
					mama_share.setText("妈妈分享");
					mama_quest.setTextColor(getResources().getColor(
							R.color.main_color));
					mama_share.setTextColor(getResources().getColor(
							R.color.black_view));
					type = "clean";
					fid = "8";
					model.setFid(fid);
					model.setFresh(zuixin);
					model.setPage_no("1");
					presenter.getInfo(model);
					// listview.addHeaderView(headermamatiwen);
					adapter.notifyDataSetChanged();
				}
			}
		});
		mama_share.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				// listview.removeHeaderView(headermamatiwen);
				if (tag) {
					tiwen_tv.setText("妈妈分享");
					showProgressDialog("妈妈分享加载中，请稍后", true);
					mama_share.setTextColor(getResources().getColor(
							R.color.main_color));
					mama_quest.setText("妈妈提问");
					mama_share.setText("・妈妈分享・");
					mama_quest.setTextColor(getResources().getColor(
							R.color.black_view));
					type = "clean";
					fid = "7";
					model.setFid(fid);
					model.setPage_no("1");
					model.setFresh(zuixin);
					presenter.getInfo(model);
					// listview.addHeaderView(headermamafenxiang);
					adapter.notifyDataSetChanged();
				}
			}
		});

	}

	@SuppressWarnings("deprecation")
	private void setbiaoqianname() {
		for (int i = 0; i < biaoqianlist.size(); i++) {
			View view = LayoutInflater.from(getActivity()).inflate(
					R.layout.textview, null);
			TextView textView = (TextView) view.findViewById(R.id.text);
			ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
			img_del.setVisibility(View.GONE);
			textView.setText(biaoqianlist.get(i).getName());
			textView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.biaoqianshape));
			textView.setTextColor(R.color.main_textcolor);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(8, 0, 8, 8);
			view.setTag(i);
			flowLayout.addView(view, lP);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							ActivityToBiaoQian.class);
					intent.putExtra("biaoqian",
							biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
									.getName());
					intent.putExtra("biaoqianID",
							biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
									.getId());
					startActivity(intent);
				}
			});
		}
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			onRefresh();
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			IntentFilter filter = new IntentFilter("update");
			getActivity().registerReceiver(receiver, filter);
			tag = true;
			if (entity.getEventType() == BiaoQianPresenter.queryBiaoQIan_success) {
				biaoqianlist
						.addAll((ArrayList<BiaoQianModel>) entity.getData());
				setbiaoqianname();

			}

			if (entity.getEventType() == TieZiPresenter.TieziFenYeSuccess) {
				if (type.equals("load")) {
				} else {
					aLists.clear();
				}
				aLists.addAll(((TieZiBaoHanReply) entity.getData()).getList());
				// if (click) {
				// adapter = new YuErJingAdapter(getActivity(),
				// ImgOnClickListener, headclick, aLists, "0",
				// deleteclick);
				// listview.setAdapter(adapter);
				// adapter.getItem(di);
				// }
				Log.e("hu", "new adapter");
				adapter.notifyDataSetChanged();
				stopLoad();
				try {
					closeProgressDialog();
				} catch (Exception e) {

				}
			} else if (entity.getEventType() == TieZiPresenter.TiezifenyeFail) {
				stopLoad();
			}

			if (entity.getEventType() == TieZiPresenter.DianzanSuccess) {
				ByAlert.alert(entity.getData() + "");
				Iterator<GetAList> iterable = aLists.iterator();
				while (iterable.hasNext()) {
					GetAList getAList = iterable.next();
					if (getAList.getTid().equals(tid)) {
						getAList.setIsLike("1");
						int count = Integer.parseInt(getAList.getLikes());
						count = count + 1;
						getAList.setLikes(count + "");
						break;
					}
				}
				adapter.notifyDataSetChanged();

			} else if (entity.getEventType() == TieZiPresenter.DianzanyeFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {

		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub

		type = "refresh";
		pageNo = 1;
		model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model.setFid(fid);
		model.setFresh(zuixin);
		model.setPage_no(pageNo + "");
		presenter.getInfo(model);
		tag = false;
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		type = "load";
		pageNo++;
		model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
				+ "");
		model.setFid(fid);
		model.setFresh(zuixin);
		model.setPage_no(pageNo + "");
		presenter.getInfo(model);
		tag = false;
	}

	public void stopLoad() {
		listview.stopLoadMore();
		listview.stopRefresh();
	}
}
